﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sharp.Infrastructure;
using Sharp.Infrastructure.IoC;
using Sharp.Platform.Interface;
using Sharp.Platform.Other;

namespace Sharp.Platform.List
{
    /// <summary>
    /// DataGrid 实现
    /// </summary>
    public class SharpList : ISharpList
    {
        private static readonly ToolButtonOperateAction Oa = new ToolButtonOperateAction();
        static SharpList()
        {
            IToolButton provider = ServiceLocator.Instance.GetService<IToolButton>();
            if (provider == null)
            {
                throw new NotImplementedException("请实现IToolButton接口或者配置好接口与实现类。");
            }

            Oa.GatherOperate("Details", provider.DetailsButton);
            Oa.GatherOperate("Create", provider.CreateButton);
            Oa.GatherOperate("Edit", provider.EditButton);
            Oa.GatherOperate("Delete", provider.DeleteButton);
            Oa.GatherOperate("Refresh", provider.RefreshButton);
            Oa.GatherOperate("Custom", provider.CustomButton);

        }

        public SharpList()
        {
            ToolbarButtonParameters = new List<ToolButtonInfo>();
        }

        public IList<ToolButtonInfo> GetToolButtons(object viewModel)
        {
            var list = new List<ToolButtonInfo>();
            foreach (DataHandlerAttribute attr in
                this.GetType().GetCustomAttributes(typeof(DataHandlerAttribute), true).OfType<DataHandlerAttribute>().OrderBy(x => x.OrderId))
            {
                var handler = attr.GetHandler();
                var datalist = viewModel as ISharpList;
                var p = datalist.ToolbarButtonParameters.FirstOrDefault(x => x.Model == attr.Mode);
                if (p != null)
                {
                    handler.Direct = p.Direct;
                    handler.Parameters = p.Parameters;
                }

                handler.Html = Oa.ExecuteOperate(attr.Mode, handler);

                list.Add(handler);
            }

            return list;
        }
        /// <summary>
        /// 特性
        /// </summary>
        public ListFeature Feature { get; set; }
        /// <summary>
        /// 按钮参数
        /// </summary>
        public IList<ToolButtonInfo> ToolbarButtonParameters { get; set; }
        

        #region 获取列表标题
        /// <summary>
        /// 获取列表标题
        /// </summary>
        /// <returns></returns>
        public string GetTitle()
        {
            var title = this.GetType().GetCustomAttributes(typeof(TitleAttribute), false).FirstOrDefault() as TitleAttribute;
            if (title != null)
            {
                return title.Title;
            }
            else
            {
                return "未定义标题";
            }
        }

        #endregion
    }
}